<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

function retailstore_add_page($id) {
    return drupal_get_form('retailstore_edit_form',$id);
}

function retailstore_edit_page($id) {
    return drupal_get_form('retailstore_edit_form', $id);
}

function retailstore_edit_form($form, &$form_state) {
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    if (!empty($id)) {
        $record = nonghua_data_load('retailstore', 'retailstore_id', $id);
        if (empty($record)) {
            drupal_set_message(t('门店不存在！'), 'status', FALSE);
            return $form;
        }
    }

    $form['submit_id'] = array(
        '#prefix' => '<div id="add_fertilizer_extra_submit-wrapper-div">',
        '#suffix' => '</div>',
        '#type' => 'hidden',
        '#title' => 'ids',
    );
    // 判断用户角色
    if(!nonghua_user_access('retailstore', 'view', $id, !empty($record) ? $record->author_uid:0, 0) ){
        drupal_set_message(t('您没有权限查看本条数据！'), 'status', FALSE);
        return $form;
    }
    insert_fertilizer_sub_info($form,$form_state,'fertilizer_case_extra');

    $form['dif_column_id'] = array(
        '#type' => 'hidden',
        '#default_value' => !empty($record)?$record->retailstore_id:''
    );
    //导入门店信息
    if(arg(1) != 'edit' && arg(1) != 'ajax') {
        $form['#attributes']['enctype'] = 'multipart/form-data';
        $form['upload_file']['file_upload_store'] = array(
            '#type' => 'file',
            '#title' => '批量导入',
            '#size' => 48
        );
        $form['upload_file']['submit'] = array(
            '#type' => 'submit',
            '#value' => '导入门店信息',
        );
    }


//    $form['retailstore'] = array(
//        '#type' => 'fieldset',
//        '#title' => '门店信息',
//        '#collapsed' => false,
//        '#collapsible' => true,
//    );
    $form['address_fuzzy'] = _insert_address_autocomplete($form, $form_state,isset($record) && !empty($record)?$record->addr_id:'');
    $form['address'] = _insert_address_selection_form($form, $form_state,'address', 5,true ,isset($record) && !empty($record)?$record->addr_id:'','省,市,县必填');
    $form['retailstore']['details'] = array(
        '#type' => 'textfield',
        '#title' => '详细地址',
        '#default_value' => !empty($record) ? $record->addr_details : '',
        '#size' => 32,
        '#maxlength' => 50,
//        '#required' => TRUE,
    );

    $form['retailstore']['name'] = array(
        '#type' => 'textfield',
        '#title' => '基层商姓名',
        '#default_value' => !empty($record) ? $record->name : '',
        '#size' => 32,
        '#maxlength' => 12,
//        '#required' => TRUE,
    );
    $form['retailstore']['tel'] = array(
        '#type' => 'textfield',
        '#title' => '电话',
        '#default_value' => !empty($record) ? $record->phone : '',
        '#size' => 32,
        '#maxlength' => 15,
//        '#required' => TRUE,
    );
    $form['brands'] = _insert_brand_checkboxes($form,$form_state,!empty($record) ? $record->brands:'');

//    $form['retailstore_sacfvariety']['sacfvariety'] = _insert_sacfvariety_selection_form(!empty($record) ? $record->sacfvariety_id:'','撒可富化肥品种',false);

    $form['retailstore']['width'] = array(
        '#type' => 'textfield',
        '#title' => '门头长度（米）',
        '#default_value' => !empty($record) ? $record->width : '',
        '#size' => 32,
//        '#maxlength' => 4,
        '#required' => FALSE,
    );
    $form['retailstore']['height'] = array(
        '#type' => 'textfield',
        '#title' => '门头高度（米）',
        '#default_value' => !empty($record) ? $record->height : '',
        '#size' => 32,
//        '#maxlength' => 4,
        '#required' => FALSE,
    );
//    $form['retailstore_plant']['plant']= _insert_plant_selection_form($form,$form_state,!empty($record) ? $record->plant_id:'');
    $form['plants']= _insert_plant_checkboxes($form,$form_state,!empty($record) ? $record->plants:'');

    $form['#retailstore_sales']['#value'] = retailstore_sales_list('retailstore_sales','retailstore_id',$id);
    $form['retailstore_plant']['area'] = array(
        '#type' => 'textfield',
        '#title' => '种植面积（亩）',
        '#default_value' => !empty($record) ? $record->farm_area : '',
//        '#required' => TRUE,
    );
    $file_ids = get_file_ids($record->retailstore_id);
    $form['#attributes']['enctype'] = 'multipart/form-data';
    $form['file_upload1'] = array(
        '#type' => 'managed_file',
        '#title' => t('Company Logo'),
//        '#description' => t('Allowed extensions: gif png jpg jpeg'),
        '#upload_location' => 'public://',
        '#default_value' => $file_ids->file_id1,
        '#theme' => 'nonghua_common_thumb_upload',
        '#upload_validators' => array(
            'file_validate_extensions' => array('gif png jpg jpeg'),
            // Pass the maximum file size in bytes
            'file_validate_size' => array(1024*1024*1024),
        ),
    );
    $form['file_upload2'] = array(
        '#type' => 'managed_file',
        '#title' => t('Company Logo'),
//        '#description' => t('Allowed extensions: gif png jpg jpeg'),
        '#upload_location' => 'public://',
        '#default_value' =>$file_ids->file_id2,
        '#theme' => 'nonghua_common_thumb_upload',
        '#upload_validators' => array(
            'file_validate_extensions' => array('gif png jpg jpeg'),
            // Pass the maximum file size in bytes
            'file_validate_size' => array(1024*1024*1024),
        ),
    );
    $form['file_upload3'] = array(
        '#type' => 'managed_file',
        '#title' => t('Company Logo'),
//        '#description' => t('Allowed extensions: gif png jpg jpeg'),
        '#upload_location' => 'public://',
        '#default_value' => $file_ids->file_id3,
        '#theme' => 'nonghua_common_thumb_upload',
        '#upload_validators' => array(
            'file_validate_extensions' => array('gif png jpg jpeg'),
            // Pass the maximum file size in bytes
            'file_validate_size' => array(1024*1024*1024),
        ),
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => arg(1) === 'edit' ? '修改' : '添加',
        '#access' =>nonghua_user_access('retailstore', 'edit', $id, !empty($record) ? $record->author_uid:0, 0) ,
    );
//    print_r($form);die;
    return $form;
}

function retailstore_edit_form_validate($form, &$form_state) {
    _address_element_validate($form_state);
    if($form_state['values']['op'] != '导入门店信息')
        {
            if(empty($form_state['values']['area'])){
                form_set_error('area', "必须填写 种植面积");
            }
            if (!empty($form_state['values']['area'])) {
                $reg = '/^\d{1,8}(.\d{0,2})?$/';
                if (!preg_match($reg, $form_state['values']['area']) || (strlen(explode('.', $form_state['values']['area'])[0]) > 8)) {
                    form_set_error('area', "种植面积格式错误");
                }
            }

            $plant_validate = false;
            $result_category = db_select('plant_category', 'b')
                ->fields('b', array('plant_category_id', 'plant_category_name'))
                ->execute();
            foreach ($result_category as $category) {
                foreach ($form_state['values'][$category->plant_category_name] as $plant) {
                    if ($plant !== 0) {
                        $plant_validate = true;
                        break;
                    }
                }
                if ($plant_validate) {
                    break;
                }
            }
            if (!$plant_validate) {
                form_set_error('plants', '必须填写 主要作物');
            }

            if (empty($form_state['values']['details'])) {
                form_set_error('details', '必须填写 详细地址');
            }
            if (empty($form_state['values']['name'])) {
                form_set_error('name', '必须填写 基层商姓名');
            }
            if(empty($form_state['values']['tel'])){
                form_set_error('tel', '必须填写 手机号');
            } else{
                $return_value = pregPN($form_state['values']['tel']);
                $return_value1 = pregTP($form_state['values']['tel']);
                if (empty($return_value)&&empty($return_value1)) {
                    form_set_error('tel', '请填写正确的 手机号');
                }
            }
            if (empty($form_state['values']['sacfvariety'])) {
                $form_state['values']['sacfvariety'] = null;
            }
        }
}

function retailstore_edit_form_submit($form, &$form_state) {
    //门店信息导入判断
    _address_element_validate($form_state);
//    print_r($form_state["values"]);die;
    if($form_state['values']['op'] == '导入门店信息'){
        if(_address_element_validate($form_state)) {
            if (!empty($_FILES['files']['name']['file_upload_store'])) {
                metercomm_import_form_submit_store($form, $form_state);
                drupal_goto('retailstore/list');
            } else {
                form_set_error('file_upload_store', "未选择Excel表格");
            }
        }
    }else {
        global $user;
        $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
        $address = _get_address_id_from_autocomplete_select($form_state);
        $brands = _get_brands_from_checkboxes_type($form_state);
        $plants = _get_plants_from_checkboxes_type($form_state);
        if (arg(1) == 'add') { //add new retailstore
            $nid = db_insert('retailstore')// Table name no longer needs {}
            ->fields(array(
                'addr_id' => $address,
                'addr_details' => $form_state['values']['details'],
                'name' => $form_state['values']['name'],
                'phone' => $form_state['values']['tel'],
//                    'sacfvariety_id' => $form_state['values']['sacfvariety'],
                'brands' => $brands,
                'plants' => $plants,
                'width' => !empty($form_state['values']['width']) ? $form_state['values']['width'] : '0',
                'height' => !empty($form_state['values']['height']) ? $form_state['values']['height'] : '0',
//                    'plant_id' => get_id_from_string_field('plant','plant_id','plant_name',$form_state['values']['plant'],false),
                'file_id1' => !empty($form_state['values']['file_upload1']) ? $form_state['values']['file_upload1'] : NULL,
                'file_id2' => !empty($form_state['values']['file_upload2']) ? $form_state['values']['file_upload2'] : NULL,
                'file_id3' => !empty($form_state['values']['file_upload3']) ? $form_state['values']['file_upload3'] : NULL,
                'farm_area' => $form_state['values']['area'],
                'author_uid' => $user->uid,
                'timestamp' => time(),))
                ->execute();
            if ($nid > 0) {
                $ids = explode(',', $form_state['values']['submit_id']);
                _update_retailstore_sales_extra($nid, $ids);
                drupal_set_message(t('添加成功！'), 'status', FALSE);
                drupal_goto('retailstore/add/' . $nid);
            }
        } else {
            $file_ids = get_file_ids($id);
            $nid = db_update('retailstore')// edit exsting store. todo: update only modified fields
            ->fields(array(
                'addr_id' => $address,
                'addr_details' => $form_state['values']['details'],
                'name' => $form_state['values']['name'],
                'phone' => $form_state['values']['tel'],
//                    'sacfvariety_id' => $form_state['values']['sacfvariety'],
                'brands' => $brands,
                'plants' => $plants,
                'width' => !empty($form_state['values']['width']) ? $form_state['values']['width'] : '0',
                'height' => !empty($form_state['values']['height']) ? $form_state['values']['height'] : '0',
//                    'plant_id' => get_id_from_string_field('plant','plant_id','plant_name',$form_state['values']['plant'],false),
                'file_id1' => !empty($form_state['values']['file_upload1']) ? $form_state['values']['file_upload1'] : $file_ids->file_id1,
                'file_id2' => !empty($form_state['values']['file_upload2']) ? $form_state['values']['file_upload2'] : $file_ids->file_id2,
                'file_id3' => !empty($form_state['values']['file_upload3']) ? $form_state['values']['file_upload3'] : $file_ids->file_id3,
                'farm_area' => $form_state['values']['area'],
                'author_uid' => $user->uid,
                'timestamp' => time(),))
                ->condition('retailstore_id', $id, '=')
                ->execute();
            if ($nid > 0) {
                drupal_set_message(t('修改成功！'), 'status', FALSE);
            }
        }
    }
}

function get_file_ids($id){
    $query = db_select('retailstore','R');
    $query->condition('R.retailstore_id',$id,'=');
    $query->fields('R',array('file_id1','file_id2','file_id3'));
    $file_ids = $query->execute()->fetchObject();
    return $file_ids;
}